package com.yeban.javase.day19.answer.test2;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Desc 模拟B/S服务器
 * @Author yeban
 * @Date 2025/11/4
 * <p>
 * 浏览器充当客户端，当访问：http://192.168.21.7:8888
 * 服务器响应HTML内容
 * 欢迎 IP 上线
 */
public class TCPServer {

    public static void main(String[] args) {
        ServerSocket ss = null;
        ThreadPool pool = new ThreadPool(10, 30);
        try {
            ss = new ServerSocket(8888);
            while (true) {
                Socket socket = ss.accept();
                pool.execute(() -> {
                    PrintStream ps = null;
                    try {
                        ps = new PrintStream(socket.getOutputStream());
                        ps.println("HTTP/1.1 200 OK");
                        ps.println("Content-Type: text/html; charset=utf-8");
                        ps.println();
                        ps.println("<html><h1 style='color:red'>欢迎" + socket.getRemoteSocketAddress() + "上线！ </h1></html>");
                        ps.flush();
                        ps.close();
                        socket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (ss != null) {
                // 关闭ServerSocket
                try {
                    ss.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
